<?php defined('SYSPATH') or die('No direct script access.');
 
class Pages
{
   // sortable page list
	public static function page_list($items,$menuset)
	{
		foreach($items as $item)
		{
			if($item->parent == 0)
			{
				// check if field 'parent' contains any ids $item->id (children)
				if(Pages::check_children($item->id) != 0)
				{
					Pages::make_children($item->id,$menuset);
					
				}else{ // if there are no children
					$view = View::factory('backend/page_tree');
					$view->menuset = $menuset;
					$view->item = $item;
					$view->array = null;
					echo $view;
				}
			}
		}
		//echo "<div id=\"sitemap_undo_alert\">Aby anulować zmiany, naciśnij Ctrl + z</div>\n";
		echo "<div id=\"sitemap_undo_alert\">Cofnij <span class=\"sitemap_undo\"><a href=\"javascript:void()\">".html::image('media/img/undo.png')."</a></span></div>\n";
	}
	
	public static function check_children($inp)
	{
		$pages = ORM::factory('page')->order_by('order','asc')->find_all();
		$output = array();
		foreach($pages as $p)
		{
			if($p->parent == $inp)
			{
				$output[] = $p->id;
			}
		}
		if(count($output) > 0)
			return $output;
			return 0;
	}
	
	public static function make_children($inp,$menuset)
	{
		$array = Pages::check_children($inp);
		$item = ORM::factory('page',$inp);
		if($array != 0)
		{
			$view = View::factory('backend/page_tree');
			$view->menuset = $menuset;
			$view->item = $item;
			$view->array = $array;
			echo $view;
		}else{
			$view = View::factory('backend/page_tree');
			$view->menuset = $menuset;
			$view->item = $item;
			$view->array = null;
			echo $view;
		}
	}
	
	public static function striptags($inp)
	{
		//$pages = ORM::factory('page')->find_all();

			# strip snippets marks [[(.*?)]]
			$split = explode('[[',$inp);
			$output = '';
			foreach($split as $s)
			{
				// searching for mark ']]'
				$match = preg_match('|\]\]|',$s);
				// if not found -> rewrite whole line
				if(!$match)
				{
					$output .= $s;
				}else{
					// if found ...
					$tiny = explode("]]",$s);
					// first part deleted
					// second part to rewrite
					$output .= $tiny[1];
				}
			}
			$output = str_replace("&nbsp;"," ",$output);
			return strip_tags($output);

	}
}